package com.yami.shop.api.controller;

import cn.hutool.core.util.IdUtil;
import com.google.zxing.WriterException;
import com.yami.shop.api.config.BarCodeUtil;
import com.yami.shop.api.config.QRCodeUtil;
import com.yami.shop.api.utils.HttpResult;
import com.yami.shop.bean.app.dto.CouponDto;
import com.yami.shop.bean.enums.SmsType;
import com.yami.shop.bean.model.Coupon;
import com.yami.shop.bean.model.CouponRecord;
import com.yami.shop.bean.model.User;
import com.yami.shop.security.util.SecurityUtils;
import com.yami.shop.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/member")
public class MemberController {

    @Autowired
    private UserService userService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private UserDepositService userDepositService;
    @Autowired
    private CouponRecordService couponRecordService;
    @Autowired
    private SmsLogService smsLogService;

    /**
     * 获取会员中心数据
     * @return
     */
    @GetMapping("/getMemberData")
    public ResponseEntity<Map> getMemberData(){
        Map map = new HashMap();
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getUserByUserId(userId);
        map.put("user",user);
        //查询优惠券的数量
        List<CouponDto> couponList = couponService.getCoupon(userId);
        map.put("couponNumber",couponList.size());
        return ResponseEntity.ok(map);
    }

    /**
     * 生成会员码
     */
    @GetMapping("/getMemberShipCode")
    public ResponseEntity<Map> getMemberShipCode(HttpServletResponse response){
        Map map = new HashMap();
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getUserByUserId(userId);
        Double userAccount = user.getUserAccount();
        if(userAccount==null){
            userAccount = 0.0;
        }
        map.put("account",userAccount);

        String mobile = null;
       //生成条形码
        String barCode = BarCodeUtil.getCode(user.getUserMobile(),50,50);
        map.put("barCode",barCode);
        //生成二维码
        try {
            String QrCode = QRCodeUtil.createQrCode(user.getUserMobile(),900,"JEPG");
            map.put("QrCode",QrCode);
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok(map);
    }


    /**
     * 新增会员
     */
    @PostMapping("/addNewMember")
    @ResponseBody
    public ResponseEntity<String> addNewMember(User user){
        //查询有没有重复的电话号码
        String mobile = user.getUserMobile();
        User oldUser = userService.selectUserByPhoneOne(mobile);
        if(oldUser!=null){
            return ResponseEntity.ok("电话号码已存在!");
        }
        //新增用户
        String userId  = IdUtil.simpleUUID();
        user.setUserId(userId);
        user.setModifyTime(new Date());
        user.setUserRegtime(new Date());
        userService.addNewMember(user);
        return  ResponseEntity.ok().build();
    }

    /**
     * 修改会员
     */
    @PostMapping("/updateMember")
    @ResponseBody
    public HttpResult updateMember(@RequestBody User user){
        //验证手机号是否正确
        String flag = smsLogService.checkValidCode(user.getUserMobile(),user.getCode(), SmsType.REGISTRATIONCODE);
        if(!flag.equals("999")){
            return HttpResult.failure(flag);
        }
        String userId = SecurityUtils.getUser().getUserId();
        User oldUser = userService.getUserByUserId(userId);
        oldUser.setUserMobile(user.getUserMobile());
        oldUser.setNickName(user.getNickName());
        oldUser.setSex(user.getSex());
        oldUser.setBirthDate(user.getBirthDate());
        userService.updateById(oldUser);
        return HttpResult.success();
    }

    /**
     * 更新会员状态
     */
    @PostMapping("/updateUser")
    @ResponseBody
    public ResponseEntity<Void> updateUser(@RequestBody User user){
        String sex = user.getSex();
        String birthDate =   user.getBirthDate();
        String userId = SecurityUtils.getUser().getUserId();
        User oldUser = userService.getUserByUserId(userId);
        oldUser.setSex(sex);
        oldUser.setBirthDate(birthDate);
        userService.updateById(oldUser);
        return  ResponseEntity.ok().build();
    }


    /**
     * 领券中心
     */
     @GetMapping("/getCoupon")
     @ResponseBody
     public  ResponseEntity<List<Coupon>>  getCoupon(){
         String userId = SecurityUtils.getUser().getUserId();
         //查询当前可以领的所有的优惠券
         List<Coupon> couponList = couponService.getAvailableCoupon();
         if(couponList.size()>0){
             for(Coupon coupon:couponList){
                 Long couponId = coupon.getCouponId();
                 //查询当前用户有没有这些优惠券的使用记录
                 CouponRecord couponRecord = couponRecordService.getAvailableCouponByUserId(couponId,userId);
                 if(couponRecord!=null){
                     coupon.setCouponRecord(couponRecord);
                 }
             }
         }
         return ResponseEntity.ok(couponList);
     }

    /**
     * 用户中心获取优惠券数量和余额
     */
    @GetMapping("/getDataOnUserCenter")
    @ResponseBody
    public ResponseEntity<Map> getDataOnUserCenter(){
        Map map = new HashMap();
        String userId = SecurityUtils.getUser().getUserId();
        //查询当前可以领的所有的优惠券
        List<Coupon> couponList = couponService.getAvailableCoupon();
        map.put("couponSize",couponList.size());

        //查询用户余额
        User user = userService.getByid(userId);
        if(user!=null){
            Double userAccount = user.getUserAccount();
            map.put("userAccount",userAccount);
        }
        return ResponseEntity.ok(map);
    }


    /**
     * 未使用的优惠券
     */
    @GetMapping("/getUnUsedCoupon")
    @ResponseBody
    public ResponseEntity<List<Coupon>> getUnUsedCoupon(){
        String userId = SecurityUtils.getUser().getUserId();
        List<Coupon> couponList = couponService.getUnUsedCoupon(userId);
        return ResponseEntity.ok(couponList);
    }

    /**
     * 已使用的优惠券
     */
    @GetMapping("/getUsedCoupon")
    @ResponseBody
    public ResponseEntity getUsedCoupon(){
        String userId = SecurityUtils.getUser().getUserId();
        List<Coupon> couponList = couponService.getUsedCoupon(userId);
        return ResponseEntity.ok().build();
    }

    /**
     * 已过期的优惠券
     */
    @GetMapping("/getOverdueCoupon")
    @ResponseBody
    public ResponseEntity getOverdueCoupon(){
        String userId = SecurityUtils.getUser().getUserId();
        List<Coupon> couponList = couponService.getOverdueCoupon(userId);
        return ResponseEntity.ok().build();
    }

}
